const app = getApp();
const api = require('../../utils/api');
const Page = require('../../utils/pageProxy');

Page({
    loginRequired: true,
    data: {
        shopId: '',
        departmentId: '',
        shopDetail: '', //店铺详情

        showBanner: false,
        bannerList: [], //广告banner列表
        categoryList: [], //分类列表

        productList: [], //推荐商品列表(废弃)
        recommendList: [], //推荐列表
        pageNum: 1,
        pageSize: 8,
        total: 0,
        noContent: false,
        isFinished: false, //加载结束
        isLoading: false, //加载中
    },
    onLoad(options) {
        if(wx.getStorageSync('shop')) {
            //第三方跳转过来，去查找对应店铺
            this.findStore();
        } else if(options.scene) {
            //从分享二维码进入，初始化数据
            wx.setStorageSync('shopId', options.scene); //缓存店铺id

            this.setData({
                shopId: options.scene ? options.scene : '',
                hasStore: options.scene ? true : false
            });

            if(this.data.hasStore) {
                this.initData();
            }
        } else {
            this.setData({
                shopId: wx.getStorageSync('shopId') ? wx.getStorageSync('shopId') : '',
                hasStore: wx.getStorageSync('shopId') ? true : false
            });

            if(this.data.hasStore) {
                this.initData();
            }
        }

        this.getCategoryList();

        //设置微信分享功能：可分享小程序和分享朋友圈
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },
    onShow() {
        if(app.globalData.isRefreshStore) {
            //刷新页面内容（重新选择社区店铺）
            app.globalData.isRefreshStore = false;
            this.setData({
                shopId: wx.getStorageSync('shopId') ? wx.getStorageSync('shopId') : '',
                hasStore: wx.getStorageSync('shopId') ? true : false
            });

            if(this.data.hasStore) {
                this.initData();
            }
        }
    },

    findStore() { //查找店铺（第三方跳转过来时）
        let params = wx.getStorageSync('shop');
        api.post(`/shop/channel?channelCode=${params.code}&channelSubCode=${params.subCode}`)
            .then(res => {
                wx.removeStorageSync('shop');

                if(res) { //如果有店铺
                    wx.setStorageSync('shopId', res); //缓存店铺id
                    this.setData({
                        shopId: res ? res : '',
                        hasStore: res ? true : false
                    });
                    if(this.data.hasStore) {
                        this.initData();
                    }  
                }
            });
    },

    initData() { //初始化页面数据
        this.setData({
            recommendList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });

        this.getStoreInfo();
    },
    getStoreInfo() { //获取店铺信息
        api.post('/shop/detail?shopId=' + this.data.shopId)
            .then(res => {
                this.setData({
                    departmentId: res.departmentId
                });
                if(this.data.departmentId === 0) { //没有所属社区的店铺
                    this.getCommunityStoreInfo();
                }
                
                this.getCommunityStoreList(); //获取社区店铺列表
            })
            .catch(err => {
                if(err.code === '200022' || err.code == '100004') {
                    setTimeout(() => {
                        this.setData({
                            hasStore: false
                        });
                    }, 1000);
                }
            })
    },
    getCommunityStoreInfo() { //获取社区店铺（主店铺）信息
        api.post('/shop/detail?shopId=0')
            .then(res => {
                wx.setNavigationBarTitle({
                    title: res.shopName
                });
                this.setData({
                    shopId: res.shopId,
                    shopDetail: res
                });
            })
    },
    getCommunityStoreList() { //获取社区店铺列表
        if(this.data.isLoading) {
            return;
        }
        this.setData({
            isLoading: true
        });

        let params = {
            departmentId: this.data.departmentId,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post(`/index/shop/recommend`, params)
            .then(res => {
                let list = res.content;
                list.forEach(item => {
                    //查找社区【主店铺】
                    if(item.shopType == 1) {
                        //设置显示栏目标题
                        wx.setNavigationBarTitle({
                            title: item.departmentName
                        });
                        this.setData({
                            shopId: item.shopId,
                            shopDetail: item
                        });
                    }
                    //整理营业时间
                    let businessBeginTime = item.businessBeginTime.split(':');
                    let businessEndTime = item.businessEndTime.split(':');
                    item.businessTime = businessBeginTime[0] + ':' + businessBeginTime[1] + '~' + businessEndTime[0] + ':' + businessEndTime[1];
                });

                //保存列表
                let newList = [...this.data.recommendList, ...list];
                this.setData({
                    recommendList: newList,
                    total: res.total,
                    showSearchResult: true,
                    isLoading: false,
                });

                //是否无内容标识
                if(this.data.recommendList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.recommendList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    });
                } else {
                    this.setData({
                        isFinished: false
                    });
                }

                this.getBannerList();
                wx.stopPullDownRefresh();
            })
    },

    getBannerList() { //获取店铺banner列表
        api.post(`/ad/ad/list?districtCode=0&moduleNo=shop-index&shopId=${this.data.shopId}`)
            .then(res => {
                this.setData({
                    bannerList: res,
                    showBanner: true
                });
            })
            .catch(() => {
                this.setData({
                    showBanner: true
                });
            })
    },
    viewBannerDetail(e) { //查看banner详情
        let item = e.currentTarget.dataset.item;
        let type = item.targetType;

        if(type == 1) { //跳转小程序指定页面
            wx.navigateTo({
                url: item.frontRoutePath + '&dir=1'
            });
        } else if(type == 3) { //跳转外部小程序
            let appId = item.apiUrl;
            let path = item.frontRoutePath;
            wx.navigateToMiniProgram({
                appId: appId,
                path: path,
                success: res => {
                    console.log('打开成功')
                }
            });
        } else { //默认页面或者公众号页面
            wx.navigateTo({
                url: '/pages/adsDetail/adsDetail?id=' + item.id
            });
        }
    },

    gotoStoreCategory(e) { //去店铺分类（点单）页面
        let item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: '/pages/storeCategory/storeCategory?id=' + item.shopId,
        });
    },

    getProductList() { //获取产品列表(**废弃)
        this.setData({
            isLoading: true
        });

        let params = {
            shopId: this.data.shopId,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post(`/product/list`, params)
            .then(res => {
                let list = res.content;
                list.forEach(item => {
                    item.price = item.price.toFixed(2);
                });
                let newList = [...this.data.productList, ...list];
                this.setData({
                    productList: newList,
                    total: res.total,
                    isLoading: false,
                });

                //是否无内容标识
                if(this.data.productList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.productList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    })
                } else {
                    this.setData({
                        isFinished: false
                    })
                }
                wx.stopPullDownRefresh();
            })
    },
    viewProductDetail(e) { //查看商品详情(**废弃)
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/productDetail/productDetail?id=${id}&shopId=${this.data.shopId}&from=${this.data.shopId}`,
        });
    },

    getCategoryList() { //获取分类（同首页）
        api.post('/index/platform/category/list')
            .then(res => {
                this.setData({
                    categoryList: res
                });
            })
    },
    gotoCategory(e) { //查看分类商品
        let item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: `/pages/indexCategoryProduct/indexCategoryProduct?categoryId=${item.id}&categoryName=${item.categoryName}&from=${this.data.shopId}`,
        });
    },
    
    gotoChangeCommunity() { //去切换社区
        wx.navigateTo({
            url: '/pages/storeChange/storeChange?shopId=' + this.data.shopId,
        });
    },
    gotoCommunityDetail() { //去查看店铺详情
        wx.navigateTo({
            url: `/pages/storeDetail/storeDetail?id=${this.data.shopId}&dir=1`,
        });
    },
    gotoCommunitySearch() { //去搜索页面
        // wx.navigateTo({
        //     url: '/pages/storeCategorySearch/storeCategorySearch?id=' + this.data.shopId,
        // });
        wx.navigateTo({
            url: `/pages/productSearch/productSearch?departmentId=${this.data.departmentId}`,
        });
    },
    gotoOrder() { //去点单
        wx.navigateTo({
            url: '/pages/storeCategory/storeCategory?id=' + this.data.shopId,
        });
    },

    onPullDownRefresh() {
        if(this.data.isLoading) {
            return;
        }
        //下拉刷新
        this.setData({
            recommendList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.getCommunityStoreList();
    },
    onReachBottom() {
        //加载更多
        if(this.data.isLoading) {
            return;
        }
        if(!this.data.isFinished) {
            this.setData({
                pageNum: this.data.pageNum+1,
                isLoading: true,
            });
            
            setTimeout(() => {
                this.getCommunityStoreList();
            }, 800);
        }
    },
    onShareAppMessage() {
        let path = '';
        if(this.data.shopId) {
            path = 'pages/storeIndex/storeIndex?id=' + this.data.shopId;
        } else {
            path = 'pages/index/index'
        }
        return {
            title: this.data.shopDetail.shopName ? this.data.shopDetail.shopName : '八桂小铺',
            desc: this.data.shopDetail.remark ? this.data.shopDetail.remark : '八桂小铺',
            path: path// 路径，传递参数到指定页面
        }
    }
})